#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import os


def read_file_lines(file_path):
    """读取文件的所有行并返回列表"""
    if not os.path.exists(file_path):
        print(f"错误：文件 '{file_path}' 不存在")
        exit(1)
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            # 读取所有行并去除每行末尾的换行符
            return [line.rstrip('\n') for line in f]
    except Exception as e:
        print(f"读取文件 '{file_path}' 时出错：{e}")
        exit(1)


def filter_lines(raw_lines, input_lines, use_include):
    """根据条件过滤raw行"""
    result = []
    
    for raw_line in raw_lines:
        # 默认保留当前行
        keep_line = True
        
        for input_line in input_lines:
            # 检查是否需要剔除该行
            if use_include:
                # include模式：只要raw行包含input行就剔除
                if input_line in raw_line:
                    keep_line = False
                    break
            else:
                # 默认模式：完全匹配才剔除
                if raw_line == input_line:
                    keep_line = False
                    break
        
        # 如果需要保留，则添加到结果中
        if keep_line:
            result.append(raw_line)
    
    return result


def output_result(result_lines, output_file=None):
    """输出结果到文件或命令行"""
    if output_file:
        try:
            with open(output_file, 'w', encoding='utf-8') as f:
                for line in result_lines:
                    f.write(line + '\n')
            print(f"结果已保存到 '{output_file}'")
        except Exception as e:
            print(f"写入文件 '{output_file}' 时出错：{e}")
            exit(1)
    else:
        # 输出到命令行
        for line in result_lines:
            print(line)


def main():
    """主函数"""
    # 创建参数解析器
    parser = argparse.ArgumentParser(description='从raw文件中剔除与input文件匹配的行')
    
    # 添加必需参数
    parser.add_argument('-i', '--input', required=True, help='指定input文件路径')
    parser.add_argument('-r', '--raw', required=True, help='指定raw文件路径')
    
    # 添加可选参数
    parser.add_argument('--include', action='store_true', help='使用包含模式，而不是完全匹配模式')
    parser.add_argument('--out', help='指定输出文件路径，默认输出到命令行')
    
    # 解析命令行参数
    args = parser.parse_args()
    
    # 读取文件内容
    input_lines = read_file_lines(args.input)
    raw_lines = read_file_lines(args.raw)
    
    # 过滤行
    result_lines = filter_lines(raw_lines, input_lines, args.include)
    
    # 输出结果
    output_result(result_lines, args.out)


if __name__ == '__main__':
    main()